import { login, logout, getInfo } from '@/api/login';
import { getUserProfile } from "@/api/system/user";
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        
        const account = userInfo.account.trim()
        const password = userInfo.password
        return new Promise((resolve, reject) => {
          login(account, password).then(res => {
            localStorage.setItem('IMAccountToken', res.data.adminToken)
            localStorage.setItem('IMAdminAccount', res.data.adminAccount)
            localStorage.setItem('IMAdminToken', res.data.imToken)
            localStorage.setItem('IMAdminUserID', res.data.level)
            setToken(res.data.adminToken)
            this.token = res.data.adminToken;
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getUserProfile({}).then(res => {
            const user = res.data
            const avatar = user.faceURL == ""  ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            // if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            //   this.roles = res.roles
            //   this.permissions = res.permissions
            // } else {
            //   this.roles = ['ROLE_DEFAULT']
            // }
            this.id = user.userID
            this.name = user.nickname
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
        })
      }
    }
  })

export default useUserStore
